package com.core.jdbc;

import java.lang.reflect.Proxy;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MySqlSession {

    private Connection conn = null;


    // 获取getMapper
    public static <T> T getMapper(Class<T> clas) {
        try {
            return (T) Proxy.newProxyInstance(clas.getClassLoader(), new Class[]{clas},
                    new MySqlAopHandle<>(clas));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public MySqlSession() {
        if (conn == null) {
            try {
                conn = SqlHelper.getConnect();
                conn.setAutoCommit(true);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public List<Map<String, Object>> queryMapList(String sql, Map<String, Object> par) throws SQLException {

        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<Map<String, Object>> list = new ArrayList<>();
        try {
            // 获得连接:
            conn.setAutoCommit(true);
            // 编写SQL：
            sql = SqlUtil.parseSql(sql, par);
            pstmt = conn.prepareStatement(sql);
            // 执行sql:
            rs = pstmt.executeQuery();
            list = SqlUtil.handleResutSet(rs);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (rs != null) {
                rs.close();
            }
            if (pstmt != null) {
                pstmt.close();
            }
        }
        return list;
    }

    public Object sqlOperate(String sql, Map<String, Object> par) throws SQLException {

        PreparedStatement pstmt = null;
        ResultSet rs = null;
        Object id = null;
        try {
            // 编写SQL：
            sql = SqlUtil.parseSql(sql, par);
            pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            // 执行sql:
            pstmt.executeUpdate();
            rs = pstmt.getGeneratedKeys();

            if (rs.next()) {
                id = rs.getObject(1);

            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        } finally {
            if (rs != null) {
                rs.close();
            }
            if (pstmt != null) {
                pstmt.close();
            }
        }
        return id;
    }

    public Object sqlOperate(String sql) throws SQLException {
        return sqlOperate(sql, new HashMap<>());
    }

    public void sqlOperateList(List<String> sqls) {

    }

    public void destory() {
        try {
            conn.close();
            conn = null;
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
